package com.mzy.javaapi.IO.JSONIO;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mzy.basics.utils.JsonUtils.JsonUtil;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author mzy
 * @Date 2022/6/9 14:39
 * @Version 1.0
 */
public class JsonExample {
    public static void main(String[] args) throws IOException {
        // 对象转Json
        Person personUpdate = new Person(223993, "王多鱼s3s", 0,"2021");
//        String finalPath = "F:\\每日脚本暂存\\2022.06月\\2022.06.09\\测试路径\\test.json";
//        JsonUtils.object2JsonFile(finalPath, person);

        // Json转对象
        String finalPath1 = "F:\\每日脚本暂存\\2022.06月\\2022.06.09\\测试路径\\test.json";
//        Person person1 = JsonUtils.jsonFile2Object(finalPath1, Person.class);
//        System.out.println(person1.toString());

        // 读对应的json
        String string = JsonUtils.readStringFromFile(finalPath1, "utf-8");
        // json字符串 转对象数组
        List<Person> personList = JSONObject.parseArray(string, Person.class);

        personList.forEach(e-> System.out.println(e));

        //先移除
        int index = -1;
        for (int i = personList.size() - 1; i >= 0; i--) {
            if(personList.get(i).getName().equals(personUpdate.getName())){
                personUpdate.setAge(personList.get(i).getAge());
                index = i;
            }
        }
        //再新增
        if(index != -1){
            personList.set(index,personUpdate);
            writeModel(finalPath1,personList);
        }

//        return index != -1;
        System.out.println("---------------------------------");
        String string1 = JsonUtils.readStringFromFile(finalPath1, "utf-8");
        // json字符串 转对象数组
        List<Person> personList3 = JSONObject.parseArray(string1, Person.class);

        personList3.forEach(e-> System.out.println(e));


    }

    // 将对象list写入json
    public static void writeModel(String finalPath,List<Person> jsonObject){
        try {
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(finalPath), StandardCharsets.UTF_8);
            String json = JSONObject.toJSONString(jsonObject,true);

            osw.write(json);
            osw.flush();
            osw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
